package com.surprise.redis;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * RedisFactory.java
 * @author nick
 * 2015年2月9日
 */
@Component
public class RedisFactory {
    private JedisPool pool;

    @Autowired
    private RedisConfig config;

    @PostConstruct
    public void init() {
        pool = new JedisPool(config.getHost(), config.getPort());
    }

    public Jedis getClient() {
        Jedis jedis = pool.getResource();
        if (config.getDb() != 0) {
            jedis.select(config.getDb());
        }
        if (StringUtils.isNotEmpty(config.getAuth())) {
            jedis.auth(config.getAuth());
        }
        return jedis;
    }

    public void returnResource(Jedis jedis) {
        pool.returnResource(jedis);
    }
}
